package com.base.component.app.push.apns;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.PrivateKey;
import java.util.UUID;

import org.springframework.core.io.ClassPathResource;

import com.base.component.app.apple.AppleAuth;
import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.framework.base.rest.HttpRequest;
import com.gitee.magic.framework.base.rest.HttpWrapper;

/**
 * https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns
 * 
 * @author zywei
 *
 */
public class ApnsPushTest {

	private static String APPID = "cn.abuyaw.app";

	private static String SANDBOX_SERVER = "https://api.sandbox.push.apple.com:443";
//	private static String PRODUCT_SERVER = "https://api.push.apple.com:443";

	public static void main(String[] args) throws Exception {
		ClassPathResource cpr = new ClassPathResource("");
		AppleAuth auth=new AppleAuth();
		PrivateKey privateKey=auth.getPrivateKey(cpr.getInputStream(), "");
		String token=auth.getJwt(APPID, "S7FSJDC5Y8", "AQD95QP7M9", privateKey);
		
		// 消息，参考：https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification
		String payload="""
				{
				   "aps" : {
				      "alert" : {
				         "title" : "Game Request",
				         "subtitle" : "Five Card Draw",
				         "body" : "Bob wants to play poker"
				      }
				   }
				}
				""";
		
		HttpRequest request=new HttpRequest(SANDBOX_SERVER);
		request.setHeader("path", "/3/device/"+"4bdb36ea1411c1b5447e785ed386d304eda60b3a37aae76ed15c16bfb23c1851");
		request.setHeader("authorization", "bearer "+token);
		request.setHeader("apns-push-type", "alert");
		request.setHeader("apns-id", UUID.randomUUID().toString());
		request.setHeader("apns-expiration", "0");
		request.setHeader("apns-priority", "10");
		request.setHeader("apns-topic", APPID);
//		request.setHeader("apns-collapse-id", "");
		request.setBodyContent(payload);
		HttpWrapper wrapper=new HttpWrapper();
		HttpURLConnection connection=wrapper.requestConnect(request);
		try {
			System.out.println(connection.getResponseCode());
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
		String content=wrapper.start(request,connection);
		System.out.println(content);

	}

}